package de.tudarmstadt.ukp.muip.fibqdojo.io.raw;

import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.common.base.Optional;
import com.google.common.collect.Lists;

import de.tudarmstadt.ukp.muip.fibqdojo.interfaces.IFIBQToken;
import de.tudarmstadt.ukp.muip.fibqdojo.japanese.JapaneseToken;

/**
 * Reads a JapaneseToken from an XML file and all the stored meta information
 * about that token.
 * 
 * @author Tobias Horsmann
 */
public class JapaneseTokenReader extends TokenReader implements RawIOJapanese_Constants {

    public JapaneseTokenReader(Node xmlSentence) {
        super(xmlSentence);
    }

    @Override
    protected IFIBQToken processToken(Element parent) {

        String[] forms = new String[] {};
        String[] lemma = new String[] {};
        String[] pos = new String[] {};
        String[] kana = new String[] {};
        String[] kei = new String[] {};
        String[] meta = new String[] {};

        NodeList childNodes = parent.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node item = childNodes.item(i);
            if (!isElementNode(item)) {
                continue;
            }
            Element element = (Element) item;
            if (isNodeNameEqualTo(element, FORM)) {
                forms = readPieces(element);
            } else if (isNodeNameEqualTo(element, LEMMA)) {
                lemma = readPieces(element);
            } else if (isNodeNameEqualTo(element, POS)) {
                pos = readPieces(element);
            } else if (isNodeNameEqualTo(element, KANA)) {
                kana = readPieces(element);
            } else if (isNodeNameEqualTo(element, KEI)) {
                kei = readPieces(element);
            } else if (isNodeNameEqualTo(element, DAN)) {
                meta = readPieces(element);
            }
        }

        return new JapaneseToken(forms, pos, lemma, kana, kei, meta);
    }

    private String[] readPieces(Element parent) {

        List<String> pieces = Lists.newArrayList();

        NodeList childNodes = parent.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node item = childNodes.item(i);
            if (!isElementNode(item)) {
                continue;
            }
            Element element = (Element) item;
            Optional<String> value = getStringValueOfElement(element, PIECE);
            if (value.isPresent()) {
                pieces.add(value.get());
            } else {
                pieces.add(" ");
            }
        }

        return pieces.toArray(new String[0]);
    }

}
